<template>
  <div class="app-container">

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['xs:commission:add']"
          v-if="optType === 'update' && !(commissionWay === '统一提成' && commissionList.length > 0 )"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="commissionList" border>
      <el-table-column type="index" label="序号" align="center" />
      <el-table-column label="回款金额" align="center" prop="returnAmount" />
      <el-table-column label="提成比例（%）" align="center" prop="commissionRatio" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="optType === 'update'">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['xs:commission:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['xs:commission:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- 添加或修改业绩规则提成对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="回款金额" prop="returnAmount">
              <el-input-number
                :min="0"
                :step="1"
                v-model="form.returnAmount"
                placeholder="请输入回款金额"
                :disabled="commissionWay === '统一提成'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="提成比例（%）" prop="commissionRatio">
              <el-input-number :min="0" :step="0.01" v-model="form.commissionRatio" placeholder="请输入提成比例" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCommission,
  getCommission,
  delCommission,
  addCommission,
  updateCommission
} from "@/api/mes/xs/commission";

export default {
  name: "Commission",
  props: {
    optType: null,
    ruleId: null,
    commissionWay: null,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 显示搜索条件
      showSearch: true,
      // 业绩规则提成表格数据
      commissionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ruleId: this.ruleId,
        returnAmount: null,
        commissionRatio: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        returnAmount: [
          {required: true, message: "回款金额不能为空", trigger: "blur"}
        ],
        commissionRatio: [
          {required: true, message: "提成比例不能为空", trigger: "blur"}
        ]
      }
    };
  },
  watch: {
    ruleId: function (newVal, oldVal) {
      if (newVal !== null && newVal !== oldVal) {
        this.queryParams.ruleId = newVal;
        this.getList();
      }
    },
    commissionWay: function (newVal, oldVal) {
      if (newVal !== oldVal) {
        if (newVal !== null && oldVal !== null) {
          this.handleSelectChange(newVal, oldVal);
        }
      }
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询业绩规则提成列表 */
    getList() {
      this.loading = true;
      listCommission(this.queryParams).then(response => {
        this.commissionList = response.data;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        ruleId: this.ruleId,
        returnAmount: null,
        commissionRatio: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加业绩规则提成";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCommission(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改业绩规则提成";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCommission(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCommission(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除业绩规则提成编号为"' + ids + '"的数据项？').then(function() {
        return delCommission(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('xs/commission/export', {
        ...this.queryParams
      }, `commission_${new Date().getTime()}.xlsx`)
    },
    /** 下拉框变化 **/
    handleSelectChange(newVal, oldVal) {
      if (newVal === '统一提成') {
        const num = this.commissionList.length;
        if (num > 1) {
          // 在提示错误前将父组件的commissionWay值改回oldVal
          this.$emit('revertCommissionWay', oldVal);
          this.$modal.msgError("请先删除阶梯提成的配置")
        }else if (num === 1) {
          const returnAmount = this.commissionList[0].returnAmount;
          if (returnAmount > 0) {
            // 在提示错误前将父组件的commissionWay值改回oldVal
            this.$emit('revertCommissionWay', oldVal);
            this.$modal.msgError("请先删除阶梯提成的配置")
          }
        }
      }
    },


  }
};
</script>
